import { useCallback, useEffect, useMemo, useState } from 'react'
import PageComponent from '@components/pageComponent'
import style from './index.module.less'
import { PullToRefresh, SpinLoading, InfiniteScroll, SearchBar } from 'antd-mobile'
import PageEmpty from '@components/pageEmpty'
import { awaitWrap, formatDate, getSearch } from '@src/assets/js/tool'
import { getCaseList } from './ajax'
import { RightOutline } from 'antd-mobile-icons'
import classNames from 'classnames'
// import uuid from 'uuid'
// import { useAppDispatch } from '@src/redux/hook'
// import { push } from '@src/redux/reducers/pages'
import { useHistory } from 'react-router-dom'
import { root } from '@src/assets/js/config'

async function getList (type, search, list, current, setList, setTotal, setLoading) {
  if (list.length === 0) {
    setList([])
  }
  setLoading(true)
  const [e, d] = await awaitWrap(getCaseList(type, search, current))
  setLoading(false)
  if (e === null && d !== null) {
    setList([...list, ...d.list])
    setTotal(d.total)
  }
}

async function loadMoreFn (search, list, current, setList, setTotal, setLoading) {
  if (list.length === 0) {
    setList([])
  }
  setLoading(true)
  const [e, d] = await awaitWrap(getCaseList(search, current))
  setLoading(false)
  if (e !== null) {
    throw new Error(e.message)
  }
  if (e === null && d !== null) {
    setList([...list, ...d.list])
    setTotal(d.total)
  }
}

function Item ({ data }) {
  // const dispatch = useAppDispatch()
  const [active, setActive] = useState(false)
  const h = useHistory()
  const date = useMemo(() => {
    return typeof data.release_datetime === 'number' && data.release_datetime > 0 ? formatDate(data.release_datetime, 'YYYY-MM-DD') : ''
  }, [data])
  return (
    <div className={classNames(style.item, {[style.active]: active})} onClick={() => {
      setActive(true)
      setTimeout(() => {
        setActive(false)
        if (typeof data.url === 'string' && data.url.length > 0) {
          window.open(data.url, '_blank')
        } else {
          h.push(`${root}/gate/public-article-detail/${data.id}`)
          // dispatch(push({ element: 'gonggaoDetail', title: '公告详情', id: uuid(), meta: { id: data.id } }))
        }
      }, 150)
    }}>
      <div className={style.left}>
        <div className={style['item-title']}>{data.title}</div>
        {date && <div className={style['item-date']}>{date}</div>}
      </div>
      <RightOutline className={style.icon} />
    </div>
  )
}

function Main () {
  const s = getSearch()
   const [loading, setLoading] = useState(false)
   const [list, setList] = useState([])
   const [total, setTotal] = useState(0)
   const [search, setSearch] = useState(s && s.search ? s.search : '')
   const [text, setText] = useState(s && s.search ? s.search : '')
   const type = useMemo(() => {
    return s && s.type ? s.type : ''
   }, [s])
   const title = useMemo(() => {
    return type.replace('黑龙江省各地市', '各').replace('司法监督', '')
   }, [type])
   const h = useHistory()
   const hasMore = useMemo(() => {
       return list.length < total
     }, [total, list])
   const loadMore = useCallback(async () => {
     await loadMoreFn(type, search, list, Math.ceil(list.length / 20) + 1, setList, setTotal, setLoading)
   }, [list, search, type])
   useEffect(() => {
     getList(type, search, [], 1, setList, setTotal, setLoading)
   }, [search, type])
  return (
    <PageComponent title={title || '文章列表'} onBack={() => h.goBack()}>
      <div className={style.container}>
        <div className={style.search}>
          <SearchBar value={text} style={{ '--background': '#f5f5f5' }} placeholder='请输入' onChange={e => {
            setText(e)
          }} onSearch={(e) => setSearch(e)} onClear={() => setSearch('')} />
        </div>
        <div className={style.body}>
          <div className={style['body-inner']}>
            <PullToRefresh onRefresh={async () => {
              getList(type, search, [], 1, setList, setTotal, setLoading)
            }}>
              {loading && list.length === 0 && (
                <div className={style.loading}>
                  <SpinLoading />
                </div>
              )}
              {
                !loading && list.length === 0 && (
                  <PageEmpty />
                )
              }
              <div className={style.list}>
                {
                  list.map((li) => {
                    return <Item key={li.id} data={li} />
                  })
                }
              </div>
              {
                list.length > 0 && <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
              }
            </PullToRefresh>
          </div>
        </div>
      </div>
    </PageComponent>
  )
}

export default Main
